package com.rui.study.algorithm.P_单链表中点;

import com.rui.study.algorithm.ListNode;

public class Solution {

    public ListNode middle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }


        return slow;
    }


    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
//        ListNode node4 = new ListNode(4);
//        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;

        System.out.println(print(node1));

        Solution solution = new Solution();
        System.out.println(print(solution.middle(node1)));

    }

    public static String print(ListNode head) {
        if (head == null) {
            return "";
        }
        String nextVal = print(head.next);
        if (nextVal.length() > 0) {
            nextVal = "->" + nextVal;
        }
        return head.val + nextVal;
    }
}
